package com.example.app.components

import android.net.wifi.hotspot2.pps.HomeSp
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController

@Composable
fun CompositionLocalSample() {
    val navController = rememberNavController()
    val user = User("yxy")
    // 使用传值需要使用CompositionLocalSample将NavHost包裹
    // value传值为把创建的user对象赋值给localActiveUser
    // 被包裹的NavHost中的所有页面都可以使用user
    CompositionLocalProvider(LocalActiveUser provides user) {
        NavHost(navController = navController, startDestination = "Home") {
            composable("Home") {
                HomeScreen {
                    navController.navigate("Detail")
                }
            }
            composable("Detail") {
                DetailScreen()
            }
        }
    }

}

@Composable
fun HomeScreen(onTap: () -> Unit) {
    Column {
        // 共享数据使用
        // current为当前user对象,name为参数
        Text(text = "${LocalActiveUser.current.name}")
        Button(onClick = {
            onTap()
        }) {
            Text(text = "navigate to detail")
        }
    }
}

@Composable
fun DetailScreen() {
    Text(text = "详情页${LocalActiveUser.current.name}")
}


// 创建一个 compositionLocalOf 对象,这个对象持有的是约束对象(User)
val LocalActiveUser = compositionLocalOf<User> {
    // 为空时报错
    error("user is null")
}

data class User(val name: String)

@Preview(
    showSystemUi = true
)
@Composable
fun CompositionLocalSamplePreview() {
    CompositionLocalSample()
}

